package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.vo.FileRelate;
import com.ruoyi.system.domain.vo.UploadFileResponse;
import io.swagger.annotations.ApiOperation;
import javafx.scene.chart.Axis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysFile;
import com.ruoyi.system.service.ISysFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 系统文件Controller
 *
 * @author ruoyi
 * @date 2024-04-07
 */
@Anonymous
@RestController
@RequestMapping("/system/file")
public class SysFileController extends BaseController {
    @Autowired
    private ISysFileService sysFileService;

    @PostMapping("/uploadFile")
    @ApiOperation("单个上传文件")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("xtlx") String xtlx) {
        SysFile fileEntity = sysFileService.storeFile(file, xtlx);

        String downPath = "/system/file/downloadFile/" + String.valueOf(fileEntity.getId());
        UploadFileResponse fileResponse = new UploadFileResponse(fileEntity.getId(), fileEntity.getFileName(), fileEntity.getOriFileName(), downPath, fileEntity.getUrl(),
                fileEntity.getFileType(), fileEntity.getSuffix(), fileEntity.getSize());

        return AjaxResult.success(fileResponse);
    }

    @GetMapping("/downloadFile/{id}")
    @ApiOperation("文件下载")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long id, HttpServletRequest request) {
        SysFile fileEntity = sysFileService.getById(id);

        Resource resource = sysFileService.loadFileAsResource(fileEntity);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        String fileName = fileEntity.getOriFileName();
        try {
            fileName = new String(fileName.getBytes("utf-8"),"ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
    }

    /**
     * 以PDF形式展示文件
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/toPdf/{id}")
    @ApiOperation("转dpf下载")
    public ResponseEntity<Resource> toPdf(@PathVariable Long id, HttpServletRequest request) {
        SysFile fileEntity = sysFileService.getById(id);

        String filePath = RuoYiConfig.getUploadPath()  + fileEntity.getUrl();
        String pdfPath = filePath.substring(0, filePath.lastIndexOf(".")) + "_compress.pdf";

        Document doc = null;
        try {
            doc = new Document(filePath);
            File pdfFile = new File(pdfPath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            doc.save(fileOS, SaveFormat.PDF);

            String fileName = pdfFile.getName();

            Resource resource = new FileSystemResource(pdfFile);

           // Try to determine file's content type
            String contentType = null;
            try {
                contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
            } catch (IOException ex) {
                logger.info("Could not determine file type.");
            }

            // Fallback to the default content type if type could not be determined
            if(contentType == null) {
                contentType = "application/octet-stream";
            }

            try {
                fileName = new String(fileName.getBytes("utf-8"),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .body(resource);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }

    @PostMapping("/listAll")
    @ApiOperation("根据条件查询列表")
    public AjaxResult listAll(@RequestBody SysFile fileEntity) {
        List<SysFile> list = sysFileService.listAll(fileEntity);
        return AjaxResult.success(list);
    }

    @PostMapping("/updateRelate")
    @ApiOperation("文件关联更新")
    public AjaxResult updateRelate(@RequestBody FileRelate fileRelate) {
        sysFileService.updateRelate(fileRelate);
        return success();
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除或批量删除")
    public AjaxResult delete(@PathVariable("id") Long id) {
        sysFileService.deleteFile(id);
        return success();
    }


    /**
     * 查询系统文件列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysFile sysFile) {
        startPage();
        List<SysFile> list = sysFileService.selectSysFileList(sysFile);
        return getDataTable(list);
    }

    /**
     * 导出系统文件列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFile sysFile) {
        List<SysFile> list = sysFileService.selectSysFileList(sysFile);
        ExcelUtil<SysFile> util = new ExcelUtil<SysFile>(SysFile.class);
        util.exportExcel(response, list, "系统文件数据");
    }

    /**
     * 获取系统文件详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysFileService.selectSysFileById(id));
    }

    /**
     * 新增系统文件
     */
    @PostMapping
    public AjaxResult add(@RequestBody SysFile sysFile) {
        return toAjax(sysFileService.insertSysFile(sysFile));
    }

    /**
     * 修改系统文件
     */
    @PutMapping
    public AjaxResult edit(@RequestBody SysFile sysFile) {
        return toAjax(sysFileService.updateSysFile(sysFile));
    }

    /**
     * 删除系统文件
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysFileService.deleteSysFileByIds(ids));
    }
}
